package com.poetry.domain.dto;

import cn.hutool.extra.pinyin.PinyinUtil;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.elasticsearch.annotations.*;
import org.springframework.data.elasticsearch.core.suggest.Completion;

import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "poems")
public class PoemDoc {
    @Id
    private Integer id;

    @MultiField(mainField = @Field(type = FieldType.Text, analyzer = "poem_analyzer"),
            otherFields = {
                    @InnerField(suffix = "raw", type = FieldType.Keyword)
            })
    private String title;

    @MultiField(
            mainField = @Field(type = FieldType.Text, analyzer = "poem_analyzer"),
            otherFields = {
                    @InnerField(suffix = "keyword", type = FieldType.Keyword)
            }
    )
    private String author;

    @Field(type = FieldType.Keyword)
    private String dynasty;

    @Field(type = FieldType.Text, analyzer = "poem_analyzer")
    private String content;

    @Field(type = FieldType.Date, format = DateFormat.date_hour_minute_second)
    @JsonProperty("create_time")
    private Date createTime;

    @CompletionField(maxInputLength = 100, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private Completion suggestTitle;

    @CompletionField(maxInputLength = 100, analyzer = "ik_max_word")
    private Completion suggestAuthor;

    @CompletionField(maxInputLength = 100, analyzer = "ik_max_word", preserveSeparators = false)
    private Completion suggestContent;

    @Field(type = FieldType.Text, analyzer = "pinyin_analyzer")
    private String pinyin;

    // 高亮字段（不存储）
    @Transient
    private String highlightedTitle;

    @Transient
    private String highlightedContent;

    @Transient
    private String highlightedAuthor;

    public void populateSuggestions() {
        this.suggestTitle = new Completion(new String[]{this.title});

        // 作者建议包含朝代信息
        String authorWithDynasty = this.author + "(" + this.dynasty + ")";
        this.suggestAuthor = new Completion(new String[]{authorWithDynasty});

        // 内容建议 - 提取前20个字符
        String contentSnippet = this.content.length() > 20 ?
                this.content.substring(0, 20) + "..." : this.content;
        this.suggestContent = new Completion(new String[]{contentSnippet});

        // 生成拼音字段（用于拼音搜索）
        this.pinyin = PinyinUtil.getPinyin(this.title + " " + this.author);
    }
}
